package org.dxy.domain.handler.productionLine;

import com.google.common.eventbus.EventBus;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dxy.domain.adapter.port.CommandHandler;
import org.dxy.domain.adapter.repository.IProductionLineRepository;
import org.dxy.domain.adapter.repository.IWorkOrderRepository;
import org.dxy.domain.command.productionLine.AssignWorkOrderToLineCommand;
import org.dxy.domain.model.aggregate.ProductionLine;
import org.dxy.domain.model.aggregate.WorkOrder;
import org.dxy.types.common.CommandResult;
import org.springframework.stereotype.Component;

/**
 * @description: 分配工单到产线命令处理器
 * @author: dxy
 * @createTime: 2025/6/26 10:30
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class AssignWorkOrderToLineCommandHandler implements CommandHandler<AssignWorkOrderToLineCommand, Void> {

    private final IProductionLineRepository productionLineRepository;
    private final IWorkOrderRepository workOrderRepository;

    private final EventBus eventBus;

    @Override
    public CommandResult<Void> handle(AssignWorkOrderToLineCommand command) {
        ProductionLine productionLine = productionLineRepository.findById(command.getLineId());
        if (productionLine == null) {
            log.error("未找到产线，command={}", command);
            return CommandResult.fail("产线不存在");
        }

        // 2. 获取工位
        WorkOrder workOrder = workOrderRepository.findById(command.getWorkOrderId());
        if (workOrder == null) {
            log.error("工单不存在，command={}", command);
            return CommandResult.fail("工单不存在");
        }

        productionLine.assignWorkOrder(command,workOrder);
        productionLineRepository.save(productionLine);
        productionLine.getDomainEvents().forEach(eventBus::post);
        productionLine.clearDomainEvents();
        
        log.info("分配工单到产线成功, command={}", command);
        return CommandResult.success("分配工单到产线成功");
    }
} 